import { computed, reactive, ref, toRefs, watch, watchEffect } from "vue";
import { listFeed, refrashFeed, syncFeeds } from "../api/feed";
import { FeedMapper } from "../mappers/FeedMapper";
import { useStore } from "vuex";
import { BugFeedVo, Dept, Feed, LocalChange, Room } from "../sql/domin";
import { LocalChangeMapper } from "../mappers/LocalChangeMapper";
import { ChangeStatus, TargetType } from "../util/Constants";
import { onLoad } from "@dcloudio/uni-app";
import { loginService } from "./login";
import { DeptMapper } from "../mappers/DeptMapper";
import { RoomMapper } from "../mappers/RoomMapper";

export function FeedDataHandle() {

	const store = useStore()

	const refrashFeedList = () => {
		FeedMapper.deleteFeed().then(() => {
			FeedMapper.deleteFeedRecord().then(() => {
				listFeed().then((res) => {
					getList().then((localFeeds) => {
						let feeds = res.data.data as Feed[]
						if (feeds.length != 0) {
							for (let feed of feeds) {
								// @ts-ignore
								delete feed.params
								// 如果本地已变更则跳过更新
								if (localFeeds.filter(i => i.feed.id == feed.id && i.change != undefined).length != 0) {
									continue
								}
								// 如果本地已存在但没更新 则 更新
								if (localFeeds.filter(i => i.feed.id == feed.id).length != 0) {
									FeedMapper.updateFeedById(feed, 'Feed')
									continue
								}
								feed.tableType = 'Feed'
								// 如果本地不存在 则直接插入
								FeedMapper.InsertFeed(feed)
							}
						}
					})
				})
			})
		})
	}

	const refrashFeedsFuture = async () => {
		let res = await refrashFeed()
		console.log(res);
		uni.setStorage({
			key: "feeds",
			data: res.data.data
		})
	}

	const syncFeed = async () => {
		let feeds = await getList()
		let count = 0
		syncFeeds(feeds.filter(it => it.change != null)).then(res => {
			let changes = res.data.data as LocalChange[]
			changes.forEach(it => {
				count += 1
				if (it.changeStatus == ChangeStatus.SYNCED) {
					LocalChangeMapper.deleteLocalChangeById(it.id as number)
					FeedMapper.updateFeedById({ id: Number.parseInt(it.targetId as string), tableStatus: '1' } as Feed, 'Feed')
				}
				if (it.changeStatus == ChangeStatus.FAIL) {
					LocalChangeMapper.deleteLocalChangeById(it.id as number)
					FeedMapper.deleteFeedById(Number.parseInt(it.targetId as string))
				}
			})
		})
		return count
	}

	const getList = async () => {
		let locals = await FeedMapper.selectFeedList(store.getters.deptId, 'Feed') as Feed[]
		console.log(locals)
		let changes = await LocalChangeMapper.selectLocalChangeList(store.getters.userId, TargetType.FEED) as LocalChange[]
		let depts = (await DeptMapper.selectDept()) as Dept[]
		let rooms = await RoomMapper.selectRoomList() as Room[]
		return locals.map(it => {
			return {
				feed: it,
				change: changes.filter(i => i.targetId == it.id)[0]
			} as BugFeedVo
		})
	}

	type FeedFutrue = {
		number: string,
		reloadDay: string,
		num: number
	}

	const feedsList = ref<FeedFutrue[]>()

	const getFeedList = () => {
		uni.getStorage({
			key: 'feeds',
			success: (res) => {
				feedsList.value = res.data
			}
		})
	}

	const feeds = ref<Array<BugFeedVo>>()

	const rooms = ref<Array<Room>>()

	onLoad(async () => {
		feeds.value = await getList() as BugFeedVo[]
		rooms.value = await RoomMapper.selectRoomListDeptId(store.getters.deptId) as Room[]
	})

	return {
		syncFeed,
		refrashFeedList,
		feeds,
		getList,
		rooms,
		refrashFeedsFuture,
		getFeedList,
		feedsList
	}
}

export function FeedDateSelect() {
	const dayWord = [
		'今天',
		'昨天'
	]

	const days = ref(0)

	const dateSelect = ref()

	const dateClick = () => {
		dateSelect.value.open()
	}

	const dateChange = (e: any) => {
		console.log(e.detail.value);
		days.value = e.detail.value
	}

	return {
		dateChange,
		dayWord,
		days,
		dateSelect,
		dateClick
	}
}

export function FeedClickHandle() {

	const currentIndex = ref(1)

	const selectIndex = ref(0)

	const content = reactive([
		{
			iconPath: '/static/feed.png',
			selectedIconPath: '/static/feed.png',
			text: '饲养列表',
			active: false
		}
	])

	watch(selectIndex, (newVal, oldVal) => {
		content[newVal].active = true
		content[oldVal].active = false
	})

	const handleChange = (index: number) => {
		currentIndex.value = index
	}

	//type 0 为 可修改 1 为不可修改
	const handleUpdate = (item: BugFeedVo) => {
		let type = '0'
		if (item.feed.tableStatus == '1'
			|| item.change == null && item.feed.tableStatus == '0' && item.feed.updatedTime != null) {
			type = '1'
		}
		uni.navigateTo({
			url: `/pages/feed/form?id=${item.feed.id}&type=${type}`
		})
	}

	return {
		content,
		currentIndex,
		handleChange,
		selectIndex,
		handleUpdate
	}

}


export function FeedFormHandle() {

	const type = ref('0')

	onLoad(async (props: any) => {
		type.value = props.type
		await getFeedInfo(props.id)
	})

	const checkKillNum = (rule: any, value: any, data: Feed, callback: any) => {
		if (value < 0) {
			callback("请输入合理的数量");
		}
		return true
	};
	const checkChangeNum = (rule: any, value: any, data: Feed, callback: any) => {
		if (value < 0) {
			return callback("请输入合理的数量");
		} else if (data.glFlag === "0" && !value) {
			callback("正常的批号换虫数量不能为空");
		}
		return true
	};
	const checkStiffNum = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || (value > data.changeNum && data.changeNum)) {
			callback("请输入合理的数量");
		}
		if (data.changeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true


	};
	const checkPupaNum = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || (value > data.changeNum && data.changeNum)) {
			callback("请输入合理的数量");
		}
		if (data.changeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true
	}
	const checkResidue = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || (value > data.changeNum && data.changeNum)) {
			callback("请输入合理的数量");
		}
		if (data.changeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true
	};
	const checkSpeChangeNum = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || (value > data.changeNum && data.changeNum)) {
			callback("请输入合理的数量");
		}
		if (data.changeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true
	};
	const checkDeathNum = (rule: any, value: any, data: Feed, callback: any) => {
		if (deathNum.value < 0) {
			callback("死亡数不能小于0");
		}
		//(333, deathNum.value)
		return true
	};
	const checkglChangeNum = (rule: any, value: any, data: Feed, callback: any) => {
		if (value < 0) {
			callback("请输入合理的数量");
		} else if (data.glFlag === "1" && !value) {
			callback("隔离批号换虫数量不能为空");
		}
		return true

	};
	const checkglStiffNum = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || (value > data.glChangeNum && data.glChangeNum)) {
			callback("请输入合理的数量");
		}
		if (data.glChangeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true

	};
	const checkglPupaNum = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || value > (data.glChangeNum && data.glChangeNum)) {
			callback("请输入合理的数量");
		}
		if (data.glChangeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true
	};
	const checkglResidue = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < 0 || value > (data.glChangeNum && data.glChangeNum)) {
			callback("请输入合理的数量");
		}
		if (data.glChangeNum && !value && value !== 0) {
			callback("数量不能为空");
		}
		return true
	};
	const checkglDeathNum = (rule: any, value: any, data: Feed, callback: any) => {
		if (glDeathNum.value < 0) {
			callback("隔离死亡数不能小于0");
		}
		return true
	};
	const checkNtReloadDay = (rule: any, value: any, data: Feed, callback: any) => {
		// @ts-ignore
		if (value < data.reloadDay) {
			callback("下次换料时间不得早于本次换料时间");
		}
		return true
	};

	const roundStiff = computed(() => {
		if ((feed.value.stiffNum && feed.value.changeNum) || (feed.value.changeNum && feed.value.stiffNum === 0)) {
			return (feed.value.stiffNum / feed.value.changeNum * 100).toFixed(2) + '%'
		}
	})
	const roundPupa = computed(() => {
		if ((feed.value.pupaNum && feed.value.changeNum) || (feed.value.changeNum && feed.value.pupaNum === 0)) {
			return (feed.value.pupaNum / feed.value.changeNum * 100).toFixed(2) + '%'
		}
	})
	const deathNum = computed<number>((): number => {
		let { changeNum, stiffNum, pupaNum, specialChange, residue } = feed.value
		if (changeNum != undefined && stiffNum != undefined && pupaNum != undefined && specialChange != undefined && residue != undefined) {
			return changeNum - stiffNum - pupaNum - specialChange - residue
		}
		return 0
	})

	const roundDeath = computed(() => {
		if (deathNum.value !== undefined && feed.value.changeNum) {
			return (deathNum.value / feed.value.changeNum * 100).toFixed(2) + '%'
		}
	})
	const glRoundStiff = computed(() => {
		if (feed.value.glStiffNum && feed.value.glChangeNum) {
			return (feed.value.glStiffNum / feed.value.glChangeNum * 100).toFixed(2) + '%'
		}
	})

	const glRoundPupa = computed(() => {
		if (feed.value.glPupaNum && feed.value.glChangeNum) {
			return (feed.value.glPupaNum / feed.value.glChangeNum * 100).toFixed(2) + '%'
		}
	})

	const glDeathNum = computed<number>((): number => {
		let { glChangeNum, glStiffNum, glPupaNum, glResidue } = feed.value
		if (glChangeNum != undefined && glStiffNum != undefined && glPupaNum != undefined && glResidue != undefined) {
			return glChangeNum - glStiffNum - glPupaNum - glResidue
		}
		return 0
	})

	const glRoundDeath = computed(() => {
		if (glDeathNum !== undefined && feed.value.glChangeNum) {
			// @ts-ignore
			return (glDeathNum.value / feed.value.glChangeNum * 100).toFixed(2) + '%'
		}
	})

	const rules = {
		remark: {
			rules: [{ maxLength: 150, errorMessage: '备注请在150字之内' }]
		},
		killNum: {
			rules: [{ required: true, errorMessage: '请输入灭活数量' }
				// ,{validateFunction: checkKillNum}
			]
		},
		nextReloadDay: {
			rules: [{ required: true, errorMessage: '请选择下次换料时间' },
				// { validateFunction: checkNtReloadDay}
			]
		},
		changeNum: {
			rules: [{ validateFunction: checkChangeNum }]
		},
		stiffNum: {
			rules: [{ validateFunction: checkStiffNum }]
		},
		pupaNum: {
			rules: [{ validateFunction: checkPupaNum }]
		},
		residue: {
			rules: [{ validateFunction: checkResidue }]
		},
		specialChange: {
			rules: [{ validateFunction: checkSpeChangeNum }]
		},
		deathNum: {
			rules: [{ validateFunction: checkDeathNum, }]
		},
		glChangeNum: {
			rules: [{ validateFunction: checkglChangeNum }]
		},
		glStiffNum: {
			rules: [{ validateFunction: checkglStiffNum }]
		},
		glPupaNum: {
			rules: [{ validateFunction: checkglPupaNum }]
		},
		glResidue: {
			rules: [{ validateFunction: checkglResidue }]
		},
		glDeathNum: {
			rules: [{ validateFunction: checkglDeathNum, }]
		}
	}

	const roomList = ref<Room[]>([])

	const deptList = ref<Dept[]>()

	const data = reactive({
		feed: {
			id: undefined,
			enterId: undefined,
			tableType: 'Feed',
			yearsMonth: '',
			dateForDay: '',
			roomId: 0,
			roomName: '',
			batchNumber: '',
			bugType: '',
			optionMonth: '',
			round: 0,
			period: 0,
			reloadDay: '',
			nextReloadDay: '',
			changeNum: 0,
			stiffNum: 0,
			roundStiff: 0,
			pupaNum: 0,
			roundPupa: 0,
			deathNum: 0,
			roundDeath: 0,
			killNum: 0,
			residue: 0,
			changeDeptId: 0,
			changeRoomId: 0,
			glBatchNumber: '',
			glChangeNum: 0,
			glStiffNum: 0,
			glRoundStiff: 0,
			glPupaNum: 0,
			glRoundPupa: 0,
			glKillNum: 0,
			glDeathNum: 0,
			glRoundDeath: 0,
			glResidue: 0,
			glChangeDeptId: 0,
			glChangeRoomId: 0,
			specialChange: 0,
			userId: 0,
			deptId: 0,
			deptName: '',
			tableStatus: '',
			createTime: '',
			createBy: '',
			updatedBy: '',
			updatedTime: '',
			remark: '',
			leaderOpinion: '',
			glFlag: '',
			killFlag: '',
		} as Feed
	})

	const { feed } = toRefs(data)

	const getFeedInfo = async (id: number) => {
		let feed = (await FeedMapper.selectFeedById(id, 'Feed') as Feed[])[0]
		// @ts-ignore
		data.feed = feed as Feed
		let allDept = await DeptMapper.selectDept() as Dept[]
		deptList.value = allDept
		roomList.value = await RoomMapper.selectRoomList() as Room[]
		data.feed.deptName = allDept.filter(it => it.deptId == data.feed.deptId)[0].deptName
		data.feed.roomName = roomList.value.filter(it => it.id == data.feed.roomId)[0].roomName
	}

	const thisRoomList = computed(() => {
		return roomList.value.map(it => {
			return { text: it.roomName, value: it.id }
		})
	})

	const changeDepts = computed(() => {
		return deptList.value?.map(it => {
			return { text: it.deptName, value: it.deptId }
		})
	})

	const changeRooms = computed(() => {
		return roomList.value.filter(it => it.deptId == feed.value.changeDeptId).map(it => {
			return { text: it.roomName, value: it.id }
		})
	})

	const glChangeRooms = computed(() => {
		return roomList.value.filter(it => it.deptId == feed.value.glChangeDeptId).map(it => {
			return { text: it.roomName, value: it.id }
		})
	})

	const showGlNum = ref(false)

	watch((): number => data.feed.glChangeNum as number, (newVal: number, oldVal: number) => {
		if (newVal != null && feed.value.batchNumber?.indexOf('GL') == -1 && newVal != '') {
			if (feed.value.glFlag != '1') {
				showGlNum.value = true
				feed.value.remark = getGlBathNumber()
			}
		} else {
			showGlNum.value = false
			feed.value.remark = ''
		}
	})

	const getGlBathNumber = () => {
		let split = feed.value?.batchNumber?.split("-") as string[];
		let header = "";
		if (split[0].indexOf('G') != -1 || split[0].indexOf('L') != -1) {//高原类型前缀长度不确定
			for (let s of split) {
				if (s.indexOf('G') != -1 || s.indexOf('L') != -1) {
					header += s;
				}
				else if (s === "YZ" || Number.parseInt(s) > 10000) {
					//等于育种或大于10000时跳出循环
					break;
				} else {
					header += "-" + s;
				}
			}
		} else {
			header = split[0];
		}
		let digOut = feed.value?.optionMonth?.split('-')[1]
		let isYZ = feed.value?.batchNumber?.indexOf("YZ") !== -1;
		let temp = new Date().getFullYear().toString().slice(2)
		return "GL" + "-" + header + "-" + temp + digOut + (isYZ ? "-YZ" : "");
	}


	return {
		feed,
		showGlNum,
		rules,
		glRoundDeath,
		glDeathNum,
		glRoundPupa,
		glRoundStiff,
		roundDeath,
		deathNum,
		roundPupa,
		roundStiff,
		changeRooms,
		changeDepts,
		glChangeRooms,
		thisRoomList,
		type
	}
}
